package ru.sgu.acm.contester;

import ru.sgu.acm.misc.Constants;
import ru.sgu.acm.model.Submit;
import ru.sgu.acm.judge.Judge;

import java.util.Properties;
import java.io.IOException;

/**
 *  This class construct Judge for testing submit, using configuration mapping file.
 *
 * @author Vitaly Goldshteyn (VitalyGoldstein@gmail.com)
 */
public class JudgeFactory {
    private static final JudgeFactory INSTANCE = new JudgeFactory();

    public static JudgeFactory getInstance() {
        return INSTANCE;
    }

    private Properties properties = new Properties();

    private JudgeFactory() {
        try {
            properties.load(JudgeFactory.class.getResourceAsStream(Constants.getJudgeMappingFileName()));
        } catch (IOException e) {
            throw new IllegalStateException("Couldn't read judge mapping properties", e);
        }
    }

    /**
     * Construct Judge for testing submit. 
     * @param submit, which will testing by returning Judge
     * @return Judge for testing Submit
     */
    @SuppressWarnings({"unchecked"})
    public Judge getJudge(Submit submit) {
        String className = properties.getProperty("pseudocontester.judge-mapping." +
                submit.getPseudoJudge());
        try {
            Class<? extends Judge> judgeClass = (Class<? extends Judge>) Class.forName(className);
            return judgeClass.newInstance();
        } catch (Exception e) {
            throw new IllegalStateException("Can not create class instance for " + className + ".", e);
        }

    }
}
